'use strict';
const db = uniCloud.database();
const _ = db.command;

exports.main = async (event, context) => {
  try {
    const { keyword, page = 1, size = 20 } = event;
    
    if (!keyword || typeof keyword !== 'string' || keyword.trim() === '') {
      return {
        code: 400,
        message: '搜索关键词不能为空'
      };
    }
    
    // 构建搜索条件
    const searchKeyword = keyword.trim();
    const condition = {
      title: db.RegExp({
        regexp: searchKeyword,
        options: 'i' // 不区分大小写
      })
    };
    
    // 计算分页参数
    const skip = (page - 1) * size;
    
    // 查询壁纸数据
    const wallpapersRes = await db.collection('wallpapers')
      .where(condition)
      .skip(skip)
      .limit(size)
      .orderBy('create_time', 'desc')
      .get();
    
    // 获取总数
    const countRes = await db.collection('wallpapers')
      .where(condition)
      .count();
    
    // 如果用户已登录，检查收藏状态
    let userFavorites = [];
    if (context.uid) {
      const favoritesRes = await db.collection('favorites')
        .where({
          user_id: context.uid,
          wallpaper_id: _.in(wallpapersRes.data.map(item => item._id))
        })
        .field({
          wallpaper_id: true
        })
        .get();
      
      userFavorites = favoritesRes.data.map(item => item.wallpaper_id);
    }
    
    // 标记收藏状态
    const wallpapers = wallpapersRes.data.map(wallpaper => ({
      ...wallpaper,
      is_favorite: userFavorites.includes(wallpaper._id)
    }));
    
    // 判断是否还有更多数据
    const hasMore = skip + size < countRes.total;
    
    return {
      code: 0,
      message: '搜索成功',
      totalCount: countRes.total,
      data: {
        list: wallpapers,
        hasMore
      }
    };
  } catch (error) {
    console.error('搜索壁纸失败:', error);
    return {
      code: 500,
      message: '搜索失败，请稍后重试'+error
    };
  }
};